package com.zcsy.seller.web.system;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;

import net.sf.json.JSONArray;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.util.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.commons.util.DateUtils;
import com.zcsy.manage.model.system.Dict;
import com.zcsy.manage.model.system.Role;
import com.zcsy.manage.model.system.RoleUser;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.service.base.IShopInfoService;
import com.zcsy.manage.service.company.IDistributionCompanyService;
import com.zcsy.manage.service.company.IOperationCompanyService;
import com.zcsy.manage.service.company.IPropertyCompanyService;
import com.zcsy.manage.service.system.IDictService;
import com.zcsy.manage.service.system.IOrgService;
import com.zcsy.manage.service.system.IRoleService;
import com.zcsy.manage.service.system.IUserService;

/**
 * @ClassName: UserController
 * @Description: 用户控制层管理类
 * @author xujl 850789178@qq.com
 * @date 2016年1月8日
 */
@Controller
@RequestMapping(value = "/user")
public class UserController {
    
    private static final int USER_STATE = 1; // 初始化新增用户状态为1

    @Autowired
    private IUserService userService;
    
    @Autowired
    private IRoleService roleService;
    
    @Autowired
    private IDictService dictService;
    
	@Autowired
	private IOperationCompanyService operationCompanyService;
	
	@Autowired
	private IPropertyCompanyService propertyCompanyService;
	
	@Autowired
	private IShopInfoService shopInfoService;
	
	@Autowired
	private IDistributionCompanyService distributionCompanyService;

    /**
     * 分页获取数据列表
     * 
     * @param pageNo
     *            起始页
     * @param uname
     *            用户名
     * @param lname
     *            登录名
     * @param req
     *            用户请求
     * @return
     */
    @RequestMapping(value = "userList", method = RequestMethod.GET)
    public String getUserListBySearchKey(Model model, Integer userType, Integer pageNo, String uname, String lname, HttpServletRequest req) {

        if (pageNo == null) {
            pageNo = Constants.PAGE_NO;
        }

        // 此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
        PageHelper.startPage(pageNo, Constants.PAGE_SIZE);
        User record = new User();

        // 用户名为不空字符串时，设置用户名
        if (!"".equals(uname)) {
            record.setUsername(uname);
        }

        // 登录名为不空字符串时，设置登录名
        if (!"".equals(lname)) {
            record.setLoginname(lname);;
        }

        if(!"".equals(userType)){
            record.setUserType(userType);
        }
        
        List<User> userList = userService.queryUser(record);
        PageInfo<User> info = new PageInfo<User>(userList);

        model.addAttribute("userInfo", info);
        model.addAttribute("uname", uname);
        model.addAttribute("lname", lname);
        model.addAttribute("userType", userType);
        model.addAttribute("currentPage", pageNo);

        return "system/user/userList";
    }
    

    /**
     * Description: 新增或修改用户对象
     * 
     * @param userVo
     *            用户对象
     * @param req
     *            用户请求
     * @return 请求结果
     * @author xujl 850789178@qq.com
     * @see
     */
    @RequestMapping(value = "editUser", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson saveOrUpdateUser(String lname,String nickname,String uname,
    		String pwd,String phone,String email,Integer sex,String orgId,String id,
    		@RequestParam(value="roles[]") String[] roles,int userType,String companyId,HttpServletRequest request) {
        RequestJson result = new RequestJson();
        
        try {
        	int flag = Constants.SQL_RESULT_ERROR;
        	
            if (!StringUtils.isEmpty(id)) {
               User userVo = userService.selectByPrimaryKey(id);
                userVo.setUsername(uname);
                userVo.setNickname(nickname);
                if(id == ""){
                    userVo.setLoginname(lname);
                    userVo.setPwd(pwd);
                }
                userVo.setSex(sex);
                userVo.setPhone(phone);
                userVo.setEmail(email);
                userVo.setOrgId(orgId);
                userVo.setUserType(userType);
                userVo.setCompanyId(companyId);
                userVo.setModifydatetime(DateUtils.gettimestamp());
                userVo.setId(id);
                flag = userService.updateByPrimaryKeySelective(userVo);
                result.setSuccess(true);
                
              //用户插入成功，插入对应的用户角色
                if(flag == Constants.SQL_RESULT_SUCCESS){
                    userService.updateRoleUser(userVo.getId(), roles);
                    result.setSuccess(true);
                }
            } else {
                User userVo = new User();
                
                userVo.setUsername(uname);
                userVo.setNickname(nickname);
                if(id == ""){
                    userVo.setLoginname(lname);
                    userVo.setPwd(pwd);
                }
                userVo.setSex(sex);
                userVo.setPhone(phone);
                userVo.setEmail(email);
                userVo.setOrgId(orgId);
                userVo.setUserType(userType);
                userVo.setCompanyId(companyId);
                if (userService.selectUserIfExists(userVo.getLoginname().toLowerCase())) {
                    result.setSuccess(false);
                    result.setMsg("用户已存在,新增失败!");
                    return result;
                }
                userVo.setId(UniqueNumberUtils.get18UniqueNumber());
                userVo.setCreatedatetime(DateUtils.gettimestamp());
                userVo.setState(USER_STATE);
                flag = userService.insert(userVo);
                result.setSuccess(true);
                
              //用户插入成功，插入对应的用户角色
                if(flag == Constants.SQL_RESULT_SUCCESS){
                    userService.updateRoleUser(userVo.getId(), roles);
                    result.setSuccess(true);
                }
            }
        } catch (Exception e) {
        	e.printStackTrace();
            result.setSuccess(false);
            result.setMsg("操作失败");
        }
        return result;
    }
    
    /**
     * 重置密码
     * 
     * @param id	用户ID
     * @param lname	登录名
     * @param pwd	密码
     * @param request
     * @return
     */
    @RequestMapping(value = "resetPwd", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson resetPwd(String id, String lname ,  String pwd , HttpServletRequest request) {
        RequestJson result = new RequestJson();
        User userVo = new User();
        
        try {
        	userVo.setId(id);
        	userVo.setPwd(pwd);
            userVo.setModifydatetime(DateUtils.gettimestamp());
            userService.updateByPrimaryKeySelective(userVo);
            result.setSuccess(true);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("操作失败");
        }
        return result;
    }

    /**
     * @Description 修改用户密码
     * @param id 用户id
     * @return 跳转页面url
     * @author liuying 1075817474@qq.com
     * @date 2016年5月11日
     * @see 
     */
    @RequestMapping(value = "changePassword", method = RequestMethod.GET)
	public String changePassword(Model model, String id) {
		try {
			if (!String.valueOf(Constants.STATE_DISABLED).equals(id)) {
				User userVo = userService.selectByPrimaryKey(id);
				model.addAttribute("user", userVo);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return "common/changePassword";
	}
    
    /**
     * @Description 保存密码
     * @param id 主键id
     * @param uname 用户名
     * @param oldPwd 当前密码
     * @param newPwd 新密码
     * @param req 用户请求
     * @return 响应结果
     * @author liuying 1075817474@qq.com
     * @date 2016年5月12日
     * @see 
     */
    @RequestMapping(value = "savePassword", method = RequestMethod.GET)
    @ResponseBody
    public RequestJson savePassword(String id, String lname, String oldPwd, String newPwd, HttpServletRequest req) {
        RequestJson result = new RequestJson();
        try {
            //校验的用户对象
        	final User user = userService.selectByPrimaryKey(id);
        	
        	//更新密码的用户对象
            User userVo = new User();
            
            //生成密匙
//        	final String oldUserKey = MD5Util.generalPassword(lname, oldPwd);
//        	final String newUserKey = MD5Util.generalPassword(lname, newPwd);
        	
        	//密码校验
			if(oldPwd.equals(user.getPwd())){
	        	userVo.setId(id);
	        	userVo.setPwd(newPwd);
	            userService.updateByPrimaryKeySelective(userVo);
	            result.setSuccess(true);
	            result.setMsg("操作成功");
			}else{
				result.setMsg("密码错误");
				result.setSuccess(false);
			}
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("操作失败");
            e.printStackTrace();
        }
        return result;
    }
    
    /**
     * @Description 修改用户状态
     * @param id
     *            用户id
     * @param state
     *            用户状态
     * @param req
     *            用户请求
     * @return 请求的结果
     * @author xujl 850789178@qq.com
     * @date 2016年1月8日
     * @see
     */
    @RequestMapping(value = "updateState", method = RequestMethod.GET)
    @ResponseBody
    public RequestJson updateState(String id, int state, @Context HttpServletRequest req) {
        RequestJson result = new RequestJson();
        try {
            userService.updateState(id, state);
            result.setSuccess(true);
            result.setMsg("操作成功");
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("操作失败");
            e.printStackTrace();
        }

        return result;
    }

    /**
     * @Description 批量删除用户
     * @param userIDs
     *            用户的id
     * @return 删除的结果
     * @author xujl 850789178@qq.com
     * @date 2016年1月8日
     * @see
     */
    @RequestMapping(value = "deletePage", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson deletePage(String userIDs,HttpServletRequest req) {

        RequestJson result = new RequestJson();
        
        try {
			String ids[] = userIDs.split("\\,");
			for (int i = 0; i < ids.length; i++ ) {
			    userService.deleteByPrimaryKey(ids[i]);
			}
			result.setSuccess(true);
		} catch (NumberFormatException e) {
	        result.setSuccess(false);
	        result.setMsg("操作失败");
		}
        return result;
    }

    /**
     * @Description 根据部门id查询该部门下的用户
     * @param orgId
     *            部门id
     * @return 查询的结果
     * @author xujl 850789178@qq.com
     * @date 2016年1月8日
     * @see
     */
    @RequestMapping(value = "getByOrgId", method = RequestMethod.GET)
    public RequestJson getByOrgId(@QueryParam("orgId") String orgId) {
        RequestJson result = new RequestJson();
        try {
            result.setObj(userService.selectByOrgId(orgId));
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
        }
        return result;
    }
    
    /**
     * @Description 根据主键查询用户
     * @param id 用户id
     * @param userType 账号类型
     * @return 查询的结果
     * @author xujl 850789178@qq.com
     * @date 2016年1月8日
     * @see
     */
    @RequestMapping(value = "selectPK", method = RequestMethod.GET)
    public String selectByPrimaryKey(Model model, @QueryParam("id") String id, Integer userType, String keyword) {
        try {
        	User user = new User();
            if (String.valueOf(Constants.STATE_DISABLED).equals(id)) {
                model.addAttribute("type", Constants.SAVE_TYPE);
                
                //当进入运营的新增页面时，默认为面向平台
                if(userType == 1){
                	user.setUserType(Constants.ADMIN_TYPE);
                }else{
                	user.setUserType(userType);
                }
            } else {
                user = userService.selectByPrimaryKey(id);
                //Org org = orgService.selectByPrimaryKey(user.getOrgId());
                //model.addAttribute("oName",org.getOrgName());
                model.addAttribute("type", Constants.EDIT_TYPE);
                model.addAttribute("roleId", user.getRoleId());
                
            }
            model.addAttribute("user", user);
            
            List<Role> roles = roleService.getRoleList(user.getUserType(),keyword);
            model.addAttribute("roles", roles);
            
            List<RoleUser> uRoles = userService.queryRoleByUserId(id);
            model.addAttribute("uRoles", uRoles);
            
            //List<Org> list = orgService.getAll();
            //model.addAttribute("orgs", list);
            
            List<Dict> userTypes = dictService.getDictFromCache("userType");
            model.addAttribute("userTypes", userTypes);
            
            model.addAttribute("operationCompanys", operationCompanyService.getAllCompany());
            model.addAttribute("propertyCompanys", propertyCompanyService.getAllCompany());
            model.addAttribute("shops", shopInfoService.getAllShopInfo());
            model.addAttribute("distributionCompanys", distributionCompanyService.getAllCompany());
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "system/user/userEdit";
    }
    
    @RequestMapping(value = "getRUser", method = RequestMethod.GET)
    public String getRUser(Model model,@QueryParam("userId") String userId, @Context HttpServletRequest req) {
        try {

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "system/user/userRole";
    }

    
    @RequestMapping(value = "updateRUser", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson updateRUser(@RequestParam(value="roles[]") String[] roles,String userId, @Context HttpServletRequest req) {
        RequestJson result = new RequestJson();
        try {
            userService.updateRoleUser(userId, roles);
            result.setSuccess(true);
        } catch (Exception e) {
            result.setMsg("操作异常");
        }
        return result;
    }
    
    @RequestMapping(value = "getRoleList", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson getRoleList(int userType,String keyword, @Context HttpServletRequest req) {
    	RequestJson result = new RequestJson();
    	try {
             List<Role> roles = roleService.getRoleList(userType,keyword);
             result.setObj(JSONArray.fromObject(roles).toString());
    		result.setSuccess(true);
    	} catch (Exception e) {
    		e.printStackTrace();
    		result.setMsg("操作异常");
    	}
    	return result;
    }

}
